package com.app.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.app.common.core.domain.entity.HivisionIDPhotosReq;
import com.app.common.core.domain.entity.HivisionIDPhotosRes;
import com.app.common.core.domain.entity.PhotoDTO;
import com.app.common.core.domain.entity.PhotoVo;
import com.app.common.qny.QiniuKodoUtil;
import com.app.common.utils.SecurityUtils;
import com.app.common.utils.http.HttpRequest;
import com.app.system.domain.UserPhoto;
import com.app.system.service.IUserPhotoService;
import com.app.system.service.lSystemPhotoService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.app.common.utils.MapUtils.toMap;
import static com.app.common.utils.tenCos.TenCosUtils.uploadTenCos;

/**
 * @author 徐朴芬
 */
@Service
public class lSystemPhotoImpl implements lSystemPhotoService {

    @Autowired
    private QiniuKodoUtil qiniuKodoUtil;

    @Autowired
    private IUserPhotoService userPhotoService;

    @Value(value = "${aliCode.code}")
    private String aliCode;

    @Value(value = "${aliCode.url}")
    private String url;

    @Value(value = "${DivisionIDPhotos.idphoto}")
    private String idphotoUrl;

    @Value("${TenCos.url}")
    private String tenCosUrl;


    @Override
    public PhotoVo getPhotoSpecs(PhotoDTO photoDTO) throws IOException {
        if (photoDTO.getImage() == null) {
            throw new IllegalArgumentException("图片不能为空");
        }

        String contentType = photoDTO.getImage().getContentType();
        if (!"image/png".equals(contentType) && !"image/jpeg".equals(contentType)) {
            throw new IllegalArgumentException("仅支持 PNG 或 JPEG 图片");
        }

        // 图片转 Base64
        String base64 = Base64.getEncoder().encodeToString(photoDTO.getImage().getBytes());
        photoDTO.setPhoto(base64);

        // 构造请求 JSON
        JSONObject json = new JSONObject();
        json.put("photo", base64);
        json.put("type", photoDTO.getType());
        json.put("spec", photoDTO.getSpec());
        json.put("bk", photoDTO.getBk());
        json.put("beauty_degree", photoDTO.getBeauty_degree());

        // Header
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + aliCode.trim());
        headers.put("Content-Type", "application/json; charset=UTF-8");

        // 请求阿里云接口
        String res = HttpRequest.postJson(url, json.toJSONString(), headers);
        JSONObject jsonObject = JSONObject.parseObject(res);
        JSONObject data = jsonObject.getJSONObject("data");
        String upUrl = data.getString("result");

        if (upUrl == null || upUrl.isEmpty()) {
            throw new RuntimeException("生成证件照失败：" + res);
        }

        // 下载临时文件
        String dir = System.getProperty("java.io.tmpdir") + File.separator + "photo_temp";
        Files.createDirectories(Paths.get(dir));
        File file = new File(dir, SecurityUtils.getLoginUser().getUserId() + "_photo_" + System.currentTimeMillis() + ".jpg");
        HttpRequest.downloadFile(upUrl, file.getPath(), null);

        // 上传到七牛云
        qiniuKodoUtil.upload(file.getPath());

        // 转成 Base64 返给前端
        String base;
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            byte[] bytes = fileInputStream.readAllBytes();
            base = Base64.getEncoder().encodeToString(bytes);
        }

        // 删除临时文件
        file.delete();

        // 返回结果
        PhotoVo photoVo = new PhotoVo();
        photoVo.setBase64(base);
        photoVo.setAliResult(upUrl);
        // 储存到数据库
        UserPhoto add = new UserPhoto();
        add.setUserId(SecurityUtils.getLoginUser().getUserId());
        add.setDeleteFlag("0");
        add.setPhoto(upUrl);
        userPhotoService.insertUserPhoto(add);
        return photoVo;

    }

    @Override
    public HivisionIDPhotosRes GetDivisionIDPhotos(HivisionIDPhotosReq h) throws Exception {
        if (h.getInput_image().isEmpty()) {
            throw new Exception("图片不能为空!");
        }
        String contentType = h.getInput_image().getContentType();
        if (!Objects.equals("image/png", contentType) && !Objects.equals("image/jpeg", contentType)) {
            throw new Exception("不受支持的图片类型,只支持jpg and png");
        }

        // 临时文件路径
        String dir = System.getProperty("java.io.tmpdir") + File.separator + "photo_temp";
        Files.createDirectories(Paths.get(dir));
        // 原图的临时地址
        String fileName = SecurityUtils.getLoginUser().getUserId() + "_photo_" + System.currentTimeMillis() + "." + FilenameUtils.getExtension(h.getInput_image().getOriginalFilename());

        File file = new File(dir, fileName);

        /**
         * 保存临时文件并设置默认参数
         */
        h.getInput_image().transferTo(file);
        h.setFaceDetectModel(HivisionIDPhotosReq.FaceDetectModel.retinaface_resnet50);
        h.setHumanMattingModel(HivisionIDPhotosReq.HumanMattingModel.birefnet_v1_lite);
        h.setBrightnessStrength(0.5f);
        h.setContrastStrength(1f);
        h.setSharpenStrength(0.6f);
        h.setBrightnessStrength(0.5f);

        // 丢给本地部署好的服务处理图片
        String res = HttpRequest.uploadFile(idphotoUrl, file, toMap(h), null);

        /**
         * 原图被本地服务处理
         */
        JSONObject json = JSONObject.parseObject(res);
        HivisionIDPhotosRes hivisionIDPhotosRes = new HivisionIDPhotosRes();
        hivisionIDPhotosRes.setImageBase64Standard(json.getString("image_base64_standard"));
        hivisionIDPhotosRes.setImageBase64Hd(json.getString("image_base64_hd"));
        if (hivisionIDPhotosRes.getImageBase64Standard().contains(",")) {
            hivisionIDPhotosRes.setImageBase64Standard(
                    hivisionIDPhotosRes.getImageBase64Standard().split(",")[1]
            );
        }

        if (hivisionIDPhotosRes.getImageBase64Hd().contains(",")) {
            hivisionIDPhotosRes.setImageBase64Hd(
                    hivisionIDPhotosRes.getImageBase64Hd().split(",")[1]
            );
        }

        /**
         * 上传到tencos桶里面 原图 标清图 高清图
         */
        // 原图干到桶里面
        String path = uploadTenCos(file);
        UserPhoto add = new UserPhoto();
        add.setImageOld(tenCosUrl + "/download?fileName=" + path);
        // 标清图干到桶里面
        byte[] hdImage = Base64.getDecoder().decode(hivisionIDPhotosRes.getImageBase64Hd());
        Files.write(file.toPath(),hdImage);
        String hd = uploadTenCos(file);
        add.setPhoto(tenCosUrl + "/download?fileName=" + hd);
        // 高清图干到桶里面
        byte[] image = Base64.getDecoder().decode(hivisionIDPhotosRes.getImageBase64Standard());
        Files.write(file.toPath(),image);
        String getImageBase64Standard = uploadTenCos(file);
        add.setPhoto(tenCosUrl + "/download?fileName=" + getImageBase64Standard);
        add.setUserId(SecurityUtils.getLoginUser().getUserId());
        add.setNewImage(tenCosUrl + "/download?fileName=" + getImageBase64Standard);
        add.setDeleteFlag("0");
        userPhotoService.insertUserPhoto(add);

        // 删除临时文件
        file.delete();
        return hivisionIDPhotosRes;
    }
}
